<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <!--          v-if="permissionStore.hasPermisson('jjdjx.cx')"-->
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="项目编号" label-col-flex="80px">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.projectCode"
                @press-enter="huiche"
              />
            </a-form-item>
            <a-form-item label="点检项目" label-col-flex="80px">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.projectName"
                @press-enter="huiche"
              />
            </a-form-item>
          </a-form>
        </div>
        <div class="my-tool-bar" style="float: right">
          <Toolbar
            :items="pageData.btnList"
            @select="selectHandler"
            @add="addHandler"
            @del="deleteHandler"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-spin
        :loading="pageData.pageLoading"
        tip="加载中"
        dot
        style="height: 100%; width: 100%; z-index: 999"
      >
        <div style="width: 100%; height: 100%">
          <encapsulation-agrid ref="table1Ref" :configaggrid="configTable1"></encapsulation-agrid>
        </div>
      </a-spin>
    </template>
    <a-drawer
      :width="340"
      :visible="drawerVisible"
      @ok="handleDrawerOk"
      @cancel="handleDrawerCancel"
      @close="handleDrawerCancel"
      unmountOnClose
    >
      <template #title>
        {{ drawerData.title }}
      </template>
      <div>
        <a-form size="small" :model="drawerData" layout="inline" ref="drawerRef">
          <a-form-item
            label="项目编号"
            field="projectCode"
            label-col-flex="80px"
            :rules="[
              { required: true, message: '项目编号必填' },
              { validator: checkNonChinese, message: '项目编号不能包含中文字符' },
            ]"
            :validate-trigger="['blur']"
          >
            <a-input
              allow-clear
              :style="{ width: '200px' }"
              class="bacClass"
              placeholder=""
              v-model="drawerData.projectCode"
              @press-enter="huiche"
            />
          </a-form-item>
          <a-form-item
            label="点检项目"
            field="projectName"
            :rules="[{ required: true, message: '点检项目必填' }]"
            :validate-trigger="['blur']"
            label-col-flex="80px"
          >
            <a-input
              allow-clear
              :style="{ width: '200px' }"
              class="bacClass"
              placeholder=""
              v-model="drawerData.projectName"
              @press-enter="huiche"
            />
          </a-form-item>
          <a-form-item
            label="机台类型"
            field="machineType"
            :rules="[{ required: true, message: '机台类型必填' }]"
            :validate-trigger="['blur']"
            label-col-flex="80px"
          >
            <a-select
              popup-container="html"
              :style="{ width: '200px' }"
              placeholder=""
              v-model="drawerData.machineType"
              multiple
            >
              <a-option v-for="item in drawerData.machineTypeList" :value="item.typeName">{{
                item.typeName
              }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label="调机类型"
            field="adjustmentType"
            :rules="[{ required: true, message: '调机类型必填' }]"
            :validate-trigger="['blur']"
            label-col-flex="80px"
          >
            <a-select
              popup-container="html"
              :style="{ width: '200px' }"
              placeholder=""
              v-model="drawerData.adjustmentType"
              multiple
            >
              <a-option v-for="item in drawerData.adjustmentTypeList" :value="item.machineTypeName"
                >{{ item.machineTypeName }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted, nextTick } from 'vue'
  import usePermission from '@/store/modules/permission'
  // import tableColumns from './tableConfig/CheckItem/table1'
  import { post, get } from '@/api/http'
  import { ElMessage } from 'element-plus'
  import { Message, Modal } from '@arco-design/web-vue'
  import buttionRender from '@/components/aggridCellRenDerer/buttionRender.vue'

  const pageData = reactive({
    projectCode: '', //项目编号
    projectName: '', //点检项目
    btnList: [], //按钮权限数组
    pageLoading: false, //页面加载
  })
  const drawerData = reactive({
    title: '',
    projectCode: '', //项目编号
    projectName: '', //点检项目
    id: '', //默认为空 只有修改时才有值
    machineType: [], //机台类型
    adjustmentType: [], //调机类型
    machineTypeList: [], //机台类型数组
    adjustmentTypeList: [], //调机类型数组
  })
  const drawerRef = ref<any>(null)
  //校验项目编号不能包含中文字符
  const checkNonChinese = (value: any, callback: (error?: string) => void) => {
    const pattern = /[\u4E00-\u9FA5]/ // 匹配中文字符的正则表达式
    if (pattern.test(value)) {
      callback(new Error('项目编号不能包含中文字符'))
    } else {
      callback()
    }
  }
  //设置权限
  // ['查询', '新增', '删除', '导出', '导入']
  const permissionStore = usePermission()

  if (true) {
    pageData.btnList.push('查询')
  }
  if (true) {
    pageData.btnList.push('新增')
  }
  if (true) {
    pageData.btnList.push('删除')
  }
  const headerShow = ref<boolean>(true)
  const drawerVisible = ref<boolean>(false)
  const table1Ref = ref<any>(null)
  const tableColumns = [
    {
      field: '',
      headerCheckboxSelection: true,
      checkboxSelection: true,
      width: 50,
      showDisabledCheckboxes: false,
      pinned: 'left',
    },
    {
      headerName: '项目编号',
      field: 'projectCode',
      width: 150,
    },
    {
      headerName: '点检项目',
      field: 'projectName',
      width: 150,
    },
    {
      headerName: '设备机型',
      field: 'machineType',
      width: 150,
      valueGetter: (params: any) => {
        return params.data.spotCheckProjectMachineTypeList
          .reduce((sum: any, cur: any) => sum + cur.machineType + ',', '')
          .slice(0, -1)
      },
    },
    {
      headerName: '调机类型',
      field: 'adjustmentType',
      width: 150,
      valueGetter: (params: any) => {
        return params.data.spotCheckProjectAdjustmentTypeList
          .reduce((sum: any, cur: any) => sum + cur.adjustmentType + ',', '')
          .slice(0, -1)
      },
    },
    {
      headerName: '创建人',
      field: 'createName',
      width: 150,
    },
    {
      headerName: '创建时间',
      field: 'createTime',
      width: 150,
    },
    {
      headerName: '最后修改人',
      field: 'updateName',
      width: 150,
    },
    {
      headerName: '最后修改时间',
      field: 'updateTime',
      width: 150,
    },
    {
      headerName: '操作',
      field: 'action',
      width: 150,
      cellRenderer: buttionRender,
      cellRendererParams: {
        buttonList: [
          {
            type: 'success',
            text: '修改',
            typeName: 'el-button',
            show: permissionStore.hasPermisson('jjdjx.xg'),
            Callback: (data: any) => {
              editHandler(data)
            },
          },
        ],
        eltagSize: 0,
      },
    },
  ]
  let configTable1 = {
    url: 'planSingle/spotCheckProject/getPageSpotCheckProject', //接口路径
    queryData: {
      projectCode: pageData.projectCode,
      projectName: pageData.projectName,
    },
    paginationShow: true, //分页是否显示
    invokeiIterface: true, //是否调用接
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tableColumns,
    fileName: 'CheckItem-1',
  }
  //查询渲染数据方法
  const doRefresh = async () => {
    pageData.pageLoading = true
    const res = await post({
      url: 'planSingle/spotCheckProject/getPageSpotCheckProject',
      data: {
        projectCode: pageData.projectCode,
        projectName: pageData.projectName,
        page: 1,
        size: 10,
      },
    })
    try {
      if (res.code == 200) {
        table1Ref.value.setdataListIterface(res.data.list)
      } else {
        ElMessage.error(res.message)
      }
    } catch (e) {
      console.log(e)
    } finally {
      pageData.pageLoading = false
    }
  }
  //查询条件输入框回车触发的方法
  const huiche = () => {
    doRefresh()
  }
  //点击查询按钮
  const selectHandler = () => {
    doRefresh()
  }
  const addHandler = async () => {
    drawerData.title = '新增'
    await getMachineType()
    await getAdjustmentType()
    drawerVisible.value = true
  }
  const editHandler = async (data: any) => {
    await getMachineType()
    await getAdjustmentType()
    drawerData.title = '修改'
    drawerData.id = data.id
    drawerData.projectCode = data.projectCode
    drawerData.projectName = data.projectName
    drawerData.machineType = data.spotCheckProjectMachineTypeList.map(
      (item: any) => item.machineType
    )
    drawerData.adjustmentType = data.spotCheckProjectAdjustmentTypeList.map(
      (item: any) => item.adjustmentType
    )
    drawerVisible.value = true
  }
  const deleteHandler = () => {
    if (table1Ref.value.getSelectedRows().length == 0) {
      ElMessage.error('请选择要删除的数据')
      return
    }
    Modal.confirm({
      title: '系统提示',
      content: '确认删除选中的数据?',
      async onOk() {
        pageData.pageLoading = true
        const res = await post({
          url: 'planSingle/spotCheckProject/deleteSpotCheckProject',
          data: table1Ref.value.getSelectedRows().map((item: any) => item.id),
        })
        try {
          if (res.code == 200) {
            ElMessage.success(res.message)
            doRefresh()
          } else {
            ElMessage.error(res.message)
          }
        } catch (e) {
          console.log(e)
        } finally {
          pageData.pageLoading = false
        }
      },
    })
  }
  //获取所有机台类型
  const getMachineType = async () => {
    const res = await post({
      url: 'planSingle/machineType/getMachineTypePara',
      data: {},
    })
    try {
      if (res.code == 200) {
        drawerData.machineTypeList = res.data
      } else {
        ElMessage.error(res.message)
      }
    } catch (e) {
      console.log(e)
    }
  }
  //获取所有调机类型
  const getAdjustmentType = async () => {
    const res = await post({
      url: 'pieceData/adjustingMachinePrice/getList',
      data: {},
    })
    try {
      if (res.code == 200) {
        drawerData.adjustmentTypeList = res.data
      } else {
        ElMessage.error(res.message)
      }
    } catch (e) {
      console.log(e)
    }
  }
  const handleDrawerOk = async () => {
    const valid = await drawerRef.value.validate()
    if (!valid) {
      const res = await post({
        url: 'planSingle/spotCheckProject/insertSpotCheckProject',
        data: {
          id: drawerData.id == '' ? '' : drawerData.id,
          projectCode: drawerData.projectCode,
          projectName: drawerData.projectName,
          spotCheckProjectMachineTypeList: drawerData.machineType.map((item: any) => {
            return { machineType: item }
          }),
          spotCheckProjectAdjustmentTypeList: drawerData.adjustmentType.map((item: any) => {
            return { adjustmentType: item }
          }),
        },
      })
      try {
        if (res.code == 200) {
          drawerVisible.value = false
          ElMessage.success(res.message)
          doRefresh()
        } else {
          ElMessage.error(res.message)
        }
      } catch (e) {
        console.log(e)
      }
    }
  }
  const handleDrawerCancel = () => {
    drawerVisible.value = false
    for (let k in drawerData) {
      drawerData[k] = ''
    }
  }
</script>
<style scoped>
  .arco-input-wrapper.arco-input-disabled {
    border: 1px solid #a29f9f !important;
  }

  .form {
    width: 100vw !important;
  }
</style>
